package spring.cloud.tasks.tasks_manager;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.common.HostUtil;
import spring.cloud.tasks.common.curator.Curator;
import spring.cloud.tasks.tasks_manager.schedule.ScheduleManager;

import java.util.UUID;

@Slf4j
@Setter
@Getter
public class TasksManager {
    public TasksManagerConnectionStateListener tasksManagerConnectionStateListener;

    private String zooKeeperClusterKey;
    private String nameSpace;
    private Curator curator;
    private ScheduleManager scheduleManager;

    public TasksManager(Curator curator, String nameSpace) {
        this.nameSpace = nameSpace;
        this.curator = curator;


        this.scheduleManager = new ScheduleManager(nameSpace, curator);

    }

    private String generateHostValue() {
        return HostUtil.cachedIpAddress + "-" + UUID.randomUUID();
    }

    /**
     * leadership election, add listeners
     */
    public void start() throws Exception {

        addConnectionLostListener();
        scheduleManager.start();
    }


    private void addConnectionLostListener() {
        tasksManagerConnectionStateListener = new TasksManagerConnectionStateListener(this, "connectionListener-for-nameSpaceSharding-" + nameSpace);
        curator.getCuratorFramework().getConnectionStateListenable().addListener(tasksManagerConnectionStateListener);
    }

    //
    public void stopWithCuratorFramework() {
        stop();
        curator.close();

    }

    /**
     * close listeners, delete leadership
     */
    public void stop() {
        scheduleManager.stop();
        try {
            if (tasksManagerConnectionStateListener != null) {
                curator.getCuratorFramework().getConnectionStateListenable().removeListener(tasksManagerConnectionStateListener);
                tasksManagerConnectionStateListener.shutdownNowUntilTerminated();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


}
